package com.supply.service.impl;

import com.sun.xml.internal.ws.api.ComponentEx;
import com.supply.mapper.CompanyGoodsMapper;
import com.supply.mapper.GoodsMapper;
import com.supply.pojo.*;
import com.supply.req.GoodsReq;
import com.supply.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private CompanyGoodsMapper companyGoodsMapper;

    @Override
    public List<Goods> queryByCondition(GoodsReq goodsReq) {
        GoodsExample example = new GoodsExample();
        GoodsExample.Criteria criteria = example.createCriteria();
        if (!ObjectUtils.isEmpty(goodsReq.getName())){
            criteria.andNameLike("%" + goodsReq.getName() + "%");
        }
        return goodsMapper.selectByExample(example);
    }

    @Override
    public List<Goods> queryAll() {
        return goodsMapper.selectByExample(null);
    }

    @Override
    public int saveOrUpdate(Goods goods) {
        if (goods.getId() == null){
            return goodsMapper.insert(goods);
        }else {
            return goodsMapper.updateByPrimaryKey(goods);
        }
    }

    @Override
    public Goods queryById(Long goodsId) {
        return goodsMapper.selectByPrimaryKey(goodsId);
    }

    @Override
    public List<Goods> queryByCompanyId(Long id) {
        //先查询出合作公司与合作商品的关联表数据
        CompanyGoodsExample companyGoodsExample = new CompanyGoodsExample();
        companyGoodsExample.createCriteria().andCompanyIdEqualTo(id);
        List<CompanyGoods> companyGoods = companyGoodsMapper.selectByExample(companyGoodsExample);

        //将合作商品数据的Id封装到list集合
        List<Long> goodsIds = new ArrayList<>();
        for (CompanyGoods companyGood : companyGoods) {
            goodsIds.add(companyGood.getGoodsId());
        }

        //查询商品集合
        GoodsExample example = new GoodsExample();
        example.createCriteria().andIdIn(goodsIds);
        return goodsMapper.selectByExample(example);
    }

}
